package com.zlay.javafx.examples.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.log4j.Logger;


public class ExLanguageUtils {
	private static Logger log = Logger.getLogger(ExLanguageUtils.class);
	
	private static Map<String, String> properties;
	
	public static Map<String, String> getConf() throws IOException {
		if(properties==null) {
			log.debug("loading language file...");
			String local = ExConfigUtils.getLocal();
			if(local==null||"".equals(local)) {
				Locale locale = Locale.getDefault();
				local = locale.getLanguage()+"_"+locale.getCountry();
			}
			String fileName = local+".lang";
	    	properties = new HashMap<String, String>();
	    	BufferedReader br = null;
			try {
				File file = new File(new File("").getCanonicalPath() + "/conf/language/"+fileName);
				if(!file.exists()) {
					file = new File(new File("").getCanonicalPath() + "/conf/language/zh_CN.lang");//默认取中文
				}
	            br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
	            String line = null;
	            while ((line = br.readLine()) != null) {
	                if(line!=null&&!"".equals(line)) {
	                	int idx = line.indexOf("=");
	                	if(idx>0&&idx<line.length()-1) {
	                		String key = line.substring(0, idx).trim();
	                		String value = line.substring(idx+1).trim();
	                		properties.put(key, value);
	                	}
	                }
	            }
	            log.debug("loading language file success.");
			} finally {
				if(br!=null) {
					try {
						br.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return properties;
	}
	
	public static String getMessage(String key) throws IOException {
		String message = (String) getConf().get(key);
		return message;
	}
}
